//
//  TSCVCLoginViewController.m
//  Tsc_IOS
//
//  Created by Rio on 15-5-11.
//  Copyright (c) 2015年 idream. All rights reserved.
//

#import "TSCVCLogin.h"
#import "TSCAppDelegate.h"
#import "TSCSDK.h"
#import "TSCVCForgetPasswd.h"
#import "TSCVCRegister.h"
#import "TSCMyDialog.h"
#import "TSCJsonUser.h"


@interface TSCVCLogin () {
    NSString * _userNameOrEmailThisText;
    NSString * _userNameOrEmailLastText;
}

@property (weak, nonatomic) IBOutlet UIImageView * ivUserFace;
@property (weak, nonatomic) IBOutlet UITextField * tfUserNameOrEmail;
@property (weak, nonatomic) IBOutlet UITextField * tfPasswd;

@end


@implementation TSCVCLogin

/**
 * 用xib作为vc视图
 *
 * @date 2015-05-13
 * @author Rio
 */
+ (id)vcLoginWithXib {
    return [[TSCVCLogin alloc]initWithNibName:@"Login" bundle:nil];
}

/**
 * 用Storyborad中的vc作为vc视图
 *
 * @date 2015-05-14
 * @author Rio
 */
+ (id)vcLoginWithStoryboard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_LOGIN];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    // 初始化属性
    // do nothing
    
    // 注册事件——监听代理
    _tfUserNameOrEmail.delegate = self;
    _tfPasswd.delegate = self;
    
    // TODO delete
    _tfUserNameOrEmail.text = @"导购小瑾";
    _tfPasswd.text = @"159357";
    //    [_ud setObject:@"小瑾" forKey:UD_USER_NAME_OR_EMAIL];
    
    // 设置上次登录成功的用户信息（头像+用户名）
    // 注：要排除用户从未登陆过SP为空的情况
    NSString * userNameOrEmail = [_ud stringForKey:UD_USER_NAME_OR_EMAIL];
    if ([TSCMyUtil isStringEmpty:userNameOrEmail] == false) {
        
        // 读取并显示用户头像
        [TSCMyUIUtil setUserPicIvWithUserOrEmail:userNameOrEmail imageView:_ivUserFace isUseDefaultPic:YES onSuccess:^{
            // 先隐藏iv
            _ivUserFace.alpha = 0;
            
            // 动画显示头像
            [UIView animateWithDuration:CONFIG_ANIMATION_DURATION_S animations:^{
                _ivUserFace.alpha = 1;
            }];
        } onFailure:^{
            // do nothing
        }];
        
        // 显示用户名（或email）
        _tfUserNameOrEmail.text = userNameOrEmail;
    }
    
    // 如果是被迫下线，需要显示dialog提示用户
    BOOL isForceLogout = [[_ud objectForKey:UD_IS_FORCE_LOGOUT ] boolValue];
    if (isForceLogout == true) {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"err_force_logout", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"btn_confirm", nil) otherButtonTitles:nil, nil];
        [alert show];
        
        // 清除标识位
        [_ud removeObjectForKey:UD_IS_FORCE_LOGOUT];
        [_ud synchronize];
    }
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void) viewDidAppear:(BOOL)animated {
    // TODO 使用这个生命周期方法没用，可能需要使用nvc的push/pop相关方法。但是没有找到，等写到这段代码再说
    // TODO 使用这个生命周期方法没用，可能需要使用nvc的push/pop相关方法。但是没有找到，等写到这段代码再说
    // TODO 使用这个生命周期方法没用，可能需要使用nvc的push/pop相关方法。但是没有找到，等写到这段代码再说
    // TODO 使用这个生命周期方法没用，可能需要使用nvc的push/pop相关方法。但是没有找到，等写到这段代码再说
    // TODO 使用这个生命周期方法没用，可能需要使用nvc的push/pop相关方法。但是没有找到，等写到这段代码再说
    // TODO 使用这个生命周期方法没用，可能需要使用nvc的push/pop相关方法。但是没有找到，等写到这段代码再说
    // 读取用户名
    // 注：之所以放在这里，是因为注册完毕后再次回到登录Activity时，需要重新读取SP
    NSString * userNameOrEmailInUd = [TSCMyUtil trim:[_ud objectForKey:UD_USER_NAME_OR_EMAIL]];
    NSString * userNameOrEmailInTf = [TSCMyUtil trim:_tfUserNameOrEmail.text];
    
    if ([TSCMyUtil isStringEmpty:userNameOrEmailInUd] == false && [userNameOrEmailInUd isEqualToString:userNameOrEmailInTf] == false) {
        _tfUserNameOrEmail.text = userNameOrEmailInUd;
    }
}

- (void) viewWillAppear:(BOOL)animated {
    // 登陆界面不需要显示导航栏
    // 注：之所以写在viewWillAppear()中是因为有可能从其他带有nvb的界面返回
    [[self navigationController]setNavigationBarHidden:YES];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark delegate

- (IBAction)userNameOrEmailEditingDidBegin:(id)sender {
    // 更新上一次文本内容
    _userNameOrEmailThisText = [TSCMyUtil trim:((UITextField *)sender).text];
}

- (IBAction)userNameOrEmailEditingChanged:(id)sender {
    // 更新这一次文本内容
    _userNameOrEmailLastText = [TSCMyUtil trim:((UITextField *)sender).text];
}

- (IBAction)userNameOrEmailEditingDidEnd:(id)sender {
    // 注册事件——更改登陆用户名，则登陆密码置空
    if([_userNameOrEmailLastText isEqualToString:_userNameOrEmailThisText] == false) {
        _tfPasswd.text = @"";
    }
    
    // 注册事件——当更换登录用户名/邮箱时，不断尝试从本地加载用户头像
    // 如果本次输入不为空，且和上次输入不相同，则读取并显示用户头像
    if([_userNameOrEmailLastText isEqualToString:_userNameOrEmailThisText] == false && [TSCMyUtil isStringEmpty:_userNameOrEmailLastText]==false){
        [TSCMyUIUtil setUserPicIvWithUserOrEmail:_userNameOrEmailLastText imageView:_ivUserFace isUseDefaultPic:YES onSuccess:^{
            // 先隐藏iv
            _ivUserFace.alpha = 0;
            
            // 动画显示头像
            [UIView animateWithDuration:CONFIG_ANIMATION_DURATION_S animations:^{
                _ivUserFace.alpha = 1;
            }];
        } onFailure:^{
            // do nothing
        }];
    }
    
}

- (IBAction)login_pre:(id)sender {
    // 关闭“可能”打开的键盘
    [self resignAllFirstResponder];
    
    NSString * userNameEmail = [TSCMyUtil trim:_tfUserNameOrEmail.text];
    NSString * passwd = [TSCMyUtil trim:_tfPasswd.text];
    
    // 校验用户名/邮箱
    if(
       [TSCMyCheckUtil checkWithString:userNameEmail regexType:RegexTypeUserName] == false
       &&
       [TSCMyCheckUtil checkWithString:userNameEmail regexType:RegexTypeEmail] == false
       ) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_input_username_email"];
        return;
    }
    
    // 校验密码
    if([TSCMyCheckUtil checkWithString:passwd regexType:RegexTypePasswd] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_input_passwd"];
        return;
    }
    
    // 先检查网络情况，若不可用，直接返回
    if([TSCMyNetworkUtil checkNetwork] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_network_unavailable"];
        return;
    }
    
    // 提示用户正在登录
    [self showDialogWithResourceKey:@"title_logining" isProcessing:YES];
    
    // 登录
    [self login_P1:userNameEmail passwd:passwd];
}

- (IBAction)btnLoginByQQClicked:(id)sender {
    [self loginBy3Party:ShareTypeQQSpace]; // 注：是QQSpace，而不是QQ
}

- (IBAction)btnLoginBySinaWeiboClicked:(id)sender {
    [self loginBy3Party:ShareTypeSinaWeibo];
}


/**
 * return键收回键盘
 *
 * @date 2015-05-15
 * @author Rio
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

/**
 * 点击空白区域收回键盘
 *
 * @date 2015-05-15
 * @author Rio
 */
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [_tfUserNameOrEmail resignFirstResponder];
    [_tfPasswd resignFirstResponder];
    
    // TODO 没有用？！
    //    [self.view resignFirstResponder];
}


- (IBAction)forgetPasswd:(id)sender {
    TSCVCForgetPasswd * vcForgetPasswd = [TSCVCForgetPasswd vcForgetPasswdWithStoryboard];
    [[self navigationController]pushViewController:vcForgetPasswd animated:YES];
    
}

- (IBAction)gotoRegister:(id)sender {
    TSCVCRegister * vcRegister = [TSCVCRegister vcRegisterWithStoryboard];
    [[self navigationController] pushViewController:vcRegister animated:YES];
    // TODO 注：因为注册成功后，再次返回登录界面，需要重新读取sp显示用户名/邮箱
    //    startActivityForResult(intent, Constants.REQUEST_CODE.REGISTER);
}



#pragma mark 私有方法

/* private */ - (void) login_P1:(NSString *)userNameOrEmail passwd:(NSString *)passwd {
    // 用随机数标识本次登录是哪台设备在登录，防止自己被自己的消息被迫退出登录
    long whoIsLogining = [TSCMyUtil generateRandNumScopedMin:0 max:NSIntegerMax];
    
    // 保存随机登录标识
    [_ud setObject:[NSNumber numberWithLong:whoIsLogining] forKey:UD_BAE_WHO_IS_LOGINING];
    [_ud synchronize];
    
    // 拼装请求
    NSMutableDictionary * reqDic = [[NSMutableDictionary alloc] init];
    [reqDic setObject:userNameOrEmail forKey:@"username_or_email"];
    [reqDic setObject:[TSCMyUtil getMD5:passwd] forKey:@"passwd"];
    [reqDic setObject:[NSNumber numberWithLong:whoIsLogining] forKey:@"who_is_logining"];
    
    // 发送请求
    [TSCMyHttpUtil postWithUrl:URL_USER_LOGIN dictionary:reqDic completionHandler:^(ServerRespType serverRespType, NSString * respString, NSDictionary *respDictionary, NSInteger code, NSString *msg, NSDictionary *contentDictionary) {
        // 服务器返回错误处理
        switch (serverRespType) {
            case ServerRespTypeSuccess:
                break;
            case ServerRespTypeErrNil:
            case ServerRespTypeErrJson: {
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_web_server_unavailable"];
                return;
            }
            case ServerRespTypeErrCode:{
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithString:msg];
                return;
            }
            default:
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_system"];
                return;
        }
        
        // 解析服务器返回
        TSCJsonUser * jsonUser = [[TSCJsonUser alloc]init];
        NSMutableArray * tagArray = [NSMutableArray array];
        [self parseSerRespAfterLogin:contentDictionary jsonUser:jsonUser tagArray:tagArray];
        
        // 在异步线程中继续后续逻辑，无需创建串行队列（注：因为不涉及UI操作，所以可以在异步线程中继续）
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self login_PP2:jsonUser tagArray:tagArray];
        });
        
    }];
}

/* private */ - (void) login_PP2:(TSCJsonUser *)jsonUser tagArray:(NSArray *)tagArray {
    
    // 更新SP
    // （1）Reg1相关
    [_ud setInteger:jsonUser.Id forKey:UD_USER_ID];
    [_ud setObject:jsonUser.name forKey:UD_USER_NAME];
    [_ud setObject:jsonUser.email forKey:UD_USER_EMAIL];
    [_ud setObject:[TSCMyUtil trim:_tfUserNameOrEmail.text] forKey:UD_USER_NAME_OR_EMAIL];
    // （2）首次登录相关
    [_ud setObject:jsonUser.loginKey forKey:UD_LOGIN_KEY];
    // （3）Reg2相关
    [_ud setInteger:jsonUser.role forKey:UD_USER_ROLE]; // 注：可能为0
    [_ud setInteger:jsonUser.cityId forKey:UD_USER_CITY_ID]; // 注：可能为0
    
    if (jsonUser.role == DB_USER_ROLE_GUIDE) {
        [_ud setObject:jsonUser.shopName forKey:UD_GUIDE_SHOP_NAME];
        [_ud setInteger:jsonUser.shopId forKey:UD_GUIDE_SHOP_ID];
        [_ud setObject:jsonUser.tel forKey:UD_USER_TEL];
    }
    // （4）其他
    [_ud setInteger:jsonUser.emailValid forKey:UD_USER_EMAIL_VALID];
    [_ud setBool:true forKey:UD_IS_NOTIFY_MSG];
    [_ud setInteger:jsonUser.lastLoginTime forKey:UD_BAE_LAST_LOGIN_TIME];
    if (jsonUser.role == DB_USER_ROLE_GUIDE) {
        [_ud setObject:jsonUser.goodsClassIds forKey:UD_GUIDE_GOODS_CLASS_IDS];
        [_ud setInteger:jsonUser.guideIsManager forKey:UD_GUIDE_IS_MANAGER];
    }
    [_ud synchronize];
    
    // 保存APP_DB
    [TSCMyDBUtil insertOrUpdateUserWithId_1:jsonUser.Id name:jsonUser.name email:jsonUser.email picUrl:jsonUser.picUrl];
    
    // 回到UI线程
    dispatch_async(dispatch_get_main_queue(), ^{
        // 关闭dialog
        [self dissmisDialog];
        
        // 由系统控制后续界面该如何跳转，并关闭当前界面
        [TSCMyUIUtil dispatchLoginUIWithVC:self ud:_ud additionalTagArray:tagArray];
        [TSCMyUIUtil removeVCItselfAndAllPreviousVC:self];
    });
}

/* private */ - (void) loginWith3Party_P1:(id<ISSPlatformUser>)userInfo {
    // 用随机数标识本次登录是哪台设备在登录，防止自己被自己的消息被迫退出登录
    long whoIsLogining = [TSCMyUtil generateRandNumScopedMin:0 max:NSIntegerMax];
    
    // 保存随机登录标识
    [_ud setObject:[NSNumber numberWithLong:whoIsLogining] forKey:UD_BAE_WHO_IS_LOGINING];
    [_ud synchronize];
    
    // 拼装请求
    NSMutableDictionary * reqDic = [[NSMutableDictionary alloc] init];
    [reqDic setObject:[NSNumber numberWithLong:[TSCMyUtil translateShareType2Tsc3UserType:[userInfo type]]] forKey:@"type"];
    [reqDic setObject:[userInfo uid] forKey:@"id_3"];
    [reqDic setObject:[userInfo nickname] forKey:@"name_3"];
    [reqDic setObject:[userInfo profileImage] forKey:@"pic_url_3"];
    [reqDic setObject:[[userInfo credential] token] forKey:@"token"];
    [reqDic setObject:[NSNumber numberWithLong:whoIsLogining] forKey:@"who_is_logining"];
    
    // 发送请求
    [TSCMyHttpUtil postWithUrl:URL_USER_LOGIN_THIRD_PARTY dictionary:reqDic completionHandler:^(ServerRespType serverRespType, NSString * respString, NSDictionary *respDictionary, NSInteger code, NSString *msg, NSDictionary *contentDictionary) {
        // 服务器返回错误处理
        switch (serverRespType) {
            case ServerRespTypeSuccess:
                break;
            case ServerRespTypeErrNil:
            case ServerRespTypeErrJson: {
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_web_server_unavailable"];
                return;
            }
            case ServerRespTypeErrCode:{
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithString:msg];
                return;
            }
            default:
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_system"];
                return;
        }
        
        // 解析服务器返回
        TSCJsonUser * jsonUser = [[TSCJsonUser alloc]init];
        NSMutableArray * tagArray = [NSMutableArray array];
        [self parseSerRespAfterLogin:contentDictionary jsonUser:jsonUser tagArray:tagArray];
        
        // 注：如果是三方登录，则需要把三方用户名填在用户名/邮箱中，以便后续保存SP
        _tfUserNameOrEmail.text = jsonUser.name;
        
       // 继续后续处理... 注意，这里复用了普通登陆的后续处理
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self login_PP2:jsonUser tagArray:tagArray];
        });
        
    }];
}

/* private */ - (void) parseSerRespAfterLogin:(NSDictionary *)contentDictionary jsonUser:(TSCJsonUser *)rJsonUser tagArray:(NSMutableArray *)rTagArray {
    // 参数检查
    NSAssert(rJsonUser != nil && rTagArray != nil, @"[E]%s:解析登录后server返回时，rJsonUser和rTagList不能为空！", __FUNCTION__);
    
    // （1）Reg1相关
    rJsonUser.Id = [[contentDictionary objectForKey:@"user_id"] intValue];
    rJsonUser.name = [contentDictionary objectForKey:@"name"];
    rJsonUser.email = [contentDictionary objectForKey:@"email"];// 备注：三方登陆时邮箱为空
    // （2）首次登录相关
    rJsonUser.loginKey = [contentDictionary objectForKey:@"login_key"];
    // （3）Reg2相关
    rJsonUser.role = [[contentDictionary objectForKey:@"role"] intValue];
    rJsonUser.cityId = [[contentDictionary objectForKey:@"city_id"] intValue];
    if (rJsonUser.role == DB_USER_ROLE_GUIDE) {
        rJsonUser.shopId = [[contentDictionary objectForKey:@"shop_id"] intValue];
        rJsonUser.shopName = [contentDictionary objectForKey:@"shop_name"];
        rJsonUser.tel = [contentDictionary objectForKey:@"tel"];
    }
    // （4）其他
    rJsonUser.emailValid = [[contentDictionary objectForKey:@"email_valid"] intValue];
    rJsonUser.guideStatus	 = [[contentDictionary objectForKey:@"guide_status"] intValue];
    rJsonUser.lastLoginTime = [[contentDictionary objectForKey:@"last_login_time"] intValue];
    rJsonUser.picUrl = [contentDictionary objectForKey:@"user_pic_url"];
    
    // 解析导购所在店铺经营的商品分类“id、名称”列表（后续绑定BAE时设定tag使用）
    // 注：如果是导购，且guide_status为正常，server才返回商品分类信息
    NSMutableArray * gcIdArray = [NSMutableArray array];
    if (rJsonUser.role == DB_USER_ROLE_GUIDE && rJsonUser.guideStatus == DB_YES) {
        NSArray * gcArray = [contentDictionary objectForKey:@"goods_class_list"];
        
        for (NSInteger i = 0, max = [gcArray count]; i < max; i++) {
            NSDictionary * gcDic = [gcArray objectAtIndex:i];
            
            [gcIdArray addObject:[gcDic objectForKey:@"id"]];
            
            [rTagArray addObject:[NSString stringWithFormat:@"%@%li_%@", BAE_TAG_PREFIX_GOODS_CLASS, rJsonUser.cityId, [gcDic objectForKey:@"name"]]];
        }
    }
    
    // 将解析好的gc_id_list保存起来，后续使用
    rJsonUser.goodsClassIds = [TSCMyUtil implodeWithGlue:@"," array:gcIdArray];
    
    // 解析导购身份是否为店长
    if (rJsonUser.role == DB_USER_ROLE_GUIDE) {
        rJsonUser.guideIsManager = [[contentDictionary objectForKey:@"guide_is_manager"]intValue];
    }
}

/* private */ - (void) resignAllFirstResponder {
    [_tfUserNameOrEmail resignFirstResponder];
    [_tfPasswd resignFirstResponder];
}

/* private */ - (void) loginBy3Party:(ShareType) shareType {
    [self showDialogWithResourceKey:@"content_3_party_login_page_opening" isProcessing:YES];
    
    [ShareSDK getUserInfoWithType:shareType authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
        // 经测，此时为主线程
        
        if (result) {
            PFQuery *query = [PFQuery queryWithClassName:@"UserInfo"];
            [query whereKey:@"uid" equalTo:[userInfo uid]];
            [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                // 经测，此时为主线程
                // 注：不能在后续代码中使用dispatch跳回主线程，否则将导致在主线程中的代码无法被执行（不知道为什么）
                
                // 关闭正在进行三方登录的提示，并提示用户正在登录
                // 注：此时三方登录已经成功了，应该继续进行app自己的登录逻辑
                [self dissmisDialog];
                [self showDialogWithResourceKey:@"content_3_party_login_req_sending" isProcessing:YES];
                
//                if ([objects count] == 0) {
//                    PFObject *newUser = [PFObject objectWithClassName:@"UserInfo"];
//                    [newUser setObject:[userInfo uid] forKey:@"uid"];
//                    [newUser setObject:[userInfo nickname] forKey:@"name"];
//                    [newUser setObject:[userInfo profileImage] forKey:@"icon"];
//                    [newUser saveInBackground];
//                    
//                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:[NSString stringWithFormat:@"欢迎注册：%@", [newUser objectForKey:@"name"]] delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
//                    [alertView show];
//                } else {
//                    PFObject *oldUser = [objects lastObject];
//                    
//                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:[NSString stringWithFormat:@"欢迎回来：%@", [oldUser objectForKey:@"name"]] delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
//                    [alertView show];
//                }
                
                // 三方登录成功后的逻辑处理
                [self loginWith3Party_P1:userInfo];
            }];
        } else {
            NSLog(@"[W]%s: 三方登录时，ShareSDK返回result为NO，三方登录类型：%i，错误信息：%@，错误码：%li，错误描述：%@", __FUNCTION__, shareType, error, [error errorCode], [error errorDescription]);
            
            [self dissmisDialog];
            
            // TODO 如果错误信息为：尚未安装QQ，则需要申请腾讯的webview登录方式
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:[NSString stringWithFormat:@"%@%@%@",NSLocalizedString(@"content_third_party_auth_failure_with_err_info_1", nil), [error errorDescription], NSLocalizedString(@"content_third_party_auth_failure_with_err_info_2", nil)] delegate:nil cancelButtonTitle:NSLocalizedString(@"btn_i_know", nil) otherButtonTitles: nil];
            [alertView show];
        }
    }];
}

- (void)dealloc {
    NSLog(@"TODO dealloc %@", self);
}


@end
